use mysql::PooledConn;

use serde::Deserialize;
use std::fs;
use toml::from_str;

#[derive(Debug, Deserialize)]
struct Config {
    pub database: Database,
    pub create: Create,
}

#[derive(Debug, Deserialize)]
struct Database {
    pub username: String,
    pub password: String,
    pub host: String,
    pub port: String,
    pub dbname: String,
}

#[derive(Debug, Deserialize)]
struct Create {
    pub tables: Vec<String>,
}

pub fn get_conn() -> PooledConn {
    let config_toml = fs::read_to_string("codegen.toml").expect("无法读取配置文件");
    // 解析TOML
    let config: Config = from_str(&config_toml).expect("配置文件解析失败");

    let pool = mysql::Pool::new(format!(
        "mysql://{}:{}@{}:{}/{}",
        config.database.username,
        config.database.password,
        config.database.host,
        config.database.port,
        config.database.dbname,
    ))
    .unwrap();
    let mut conn = pool.get_conn().unwrap();
    conn
}

pub fn get_dbname_tables() -> (String, Vec<String>) {
    let config_toml = fs::read_to_string("codegen.toml").expect("无法读取配置文件");
    // 解析TOML
    let config: Config = from_str(&config_toml).expect("配置文件解析失败");
    (config.database.dbname, config.create.tables)
}
